package com.lyf.controller;

import com.alibaba.druid.util.StringUtils;
import com.lyf.pojo.User;
import com.lyf.service.UserService;
import com.lyf.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    //分页查询
    @GetMapping("findByPage")
    public Map<String, Object> findByPage(Integer pageNow, Integer rows){
        Map<String,Object> result = new HashMap<>();
        pageNow = pageNow == null ? 1 : pageNow;
        rows = rows == null ? 4 : rows;
        List<User> users = userService.findByPage(pageNow,rows);
        Integer total = userService.findTotal();

        result.put("users",users);
        result.put("total", total);
        return result;
    }

    @GetMapping("findAll")
    public List<User> findAll(){
        return userService.findAll();
    }
    //保存用户
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody User user){
        Result result = new Result();
        try{
            if(user.getId()==null) {
                userService.saveUser(user);
                result.setMsg("用户信息保存成功");
            } else {
                userService.update(user);
                result.setMsg("用户信息编辑成功");
            }
        } catch (Exception e){
            result.setStatus(false);
            result.setMsg("系统错误：保存用户信息失败");
        }
        return result;
    }
    //删除用户
    @GetMapping("delete")
    public Result delete(Integer id){
        Result result = new Result();
        try{
            userService.delete(id);
            result.setMsg("删除用户成功");
        } catch (Exception e){
            result.setStatus(false);
            result.setMsg("系统错误：删除用户失败");
        }
        return result;
    }

}
